<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import DialogForm from '@/components/DialogForm.vue'
import { listMedicine, getMedicine, addMedicine, updateMedicine, delMedicine } from '@/api/medicine'
import { listCategory } from '@/api/category'

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  if (isNaN(date.getTime())) return dateTime;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 表格数据
const tableData = ref([])
// 加载状态
const loading = ref(false)
// 分类列表
const categoryList = ref([])
// 表格列配置
const columns = [
  { prop: 'medicineName', label: '药品名称', width: '180' },
  { prop: 'description', label: '药品说明' },
  { 
    prop: 'categoryId', 
    label: '药品分类', 
    width: '120',
    formatter: (val) => {
      const category = categoryList.value.find(item => item.id === val)
      return category ? category.categoryName : ''
    }
  },
  { 
    prop: 'price', 
    label: '单价', 
    width: '120',
    formatter: (val) => `¥${(val / 100).toFixed(2)}`
  },
  { prop: 'createTime', label: '添加时间', width: '180', formatter: (val) => formatDateTime(val) }
]
// 搜索字段
const searchFields = ['medicineName', 'description']

// 表单数据
const formData = reactive({
  id: null,
  medicineName: '',
  description: '',
  categoryId: null,
  price: 0,
  createTime: ''
})

// 表单字段配置 - 编辑模式
const editFormFields = ref([
  { prop: 'medicineName', label: '药品名称', type: 'input', required: true },
  { prop: 'description', label: '药品说明', type: 'textarea', rows: 4 },
  { 
    prop: 'categoryId', 
    label: '药品分类', 
    type: 'select', 
    required: true,
    options: []
  },
  { 
    prop: 'price', 
    label: '单价(元)', 
    type: 'number', 
    required: true,
    min: 0,
    precision: 2,
    step: 0.01
  }
])

// 表单字段配置 - 查看模式
const viewFormFields = ref([
  { prop: 'medicineName', label: '药品名称', type: 'input', readonly: true },
  { prop: 'description', label: '药品说明', type: 'textarea', rows: 4, readonly: true },
  { 
    prop: 'categoryId', 
    label: '药品分类', 
    type: 'select', 
    disabled: true,
    options: []
  },
  { 
    prop: 'price', 
    label: '单价(元)', 
    type: 'number', 
    disabled: true
  },
  { prop: 'createTime', label: '添加时间', type: 'input', readonly: true }
])

// 表单规则
const formRules = {
  medicineName: [
    { required: true, message: '请输入药品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 255, message: '长度不能超过 255 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择药品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { type: 'number', min: 0, message: '单价不能小于0', trigger: 'blur' }
  ]
}

// 对话框配置
const dialogConfig = reactive({
  visible: false,
  title: '添加药品',
  isEdit: false,
  isView: false
})

// 获取药品列表
const getMedicineList = async () => {
  loading.value = true
  try {
    tableData.value = await listMedicine()
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    categoryList.value = await listCategory()
    // 更新表单字段配置中的分类选项
    const categoryOptions = categoryList.value.map(item => ({
      label: item.categoryName,
      value: item.id
    }))
    
    // 更新分类选项
    editFormFields.value.find(item => item.prop === 'categoryId').options = categoryOptions
    viewFormFields.value.find(item => item.prop === 'categoryId').options = categoryOptions
  } catch (error) {
    console.error('获取分类列表失败', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 添加药品
const handleAdd = () => {
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    if (key === 'price') {
      formData[key] = 0
    } else {
      formData[key] = key === 'categoryId' ? null : ''
    }
  })
  formData.id = null
  
  dialogConfig.title = '添加药品'
  dialogConfig.isEdit = false
  dialogConfig.isView = false
  dialogConfig.visible = true
}

// 编辑药品
const handleEdit = async (row) => {
  try {
    const res = await getMedicine(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        if (key === 'price' && res[key] !== undefined) {
          // 将分转换为元
          formData[key] = res[key] / 100
        } else {
          formData[key] = res[key] || ''
        }
      })
      
      dialogConfig.title = '编辑药品'
      dialogConfig.isEdit = true
      dialogConfig.isView = false
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取药品详情失败', error)
    ElMessage.error('获取药品详情失败')
  }
}

// 查看药品
const handleView = async (row) => {
  try {
    const res = await getMedicine(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        if (key === 'price' && res[key] !== undefined) {
          // 将分转换为元
          formData[key] = res[key] / 100
        } else {
          formData[key] = res[key] || ''
        }
      })
      
      dialogConfig.title = '查看药品'
      dialogConfig.isEdit = false
      dialogConfig.isView = true
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取药品详情失败', error)
    ElMessage.error('获取药品详情失败')
  }
}

// 删除药品
const handleDelete = async (row) => {
  try {
    ElMessageBox.confirm('确定要删除该药品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await delMedicine(row.id)
      ElMessage.success('删除成功')
      getMedicineList()
    }).catch(() => {})
  } catch (error) {
    console.error('删除药品失败', error)
    ElMessage.error('删除药品失败')
  }
}

// 批量删除药品
const handleBatchDelete = async (rows) => {
  try {
    ElMessageBox.confirm(`确定要删除选中的 ${rows.length} 个药品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await Promise.all(rows.map(row => delMedicine(row.id)))
      ElMessage.success('批量删除成功')
      getMedicineList()
    }).catch(() => {})
  } catch (error) {
    console.error('批量删除药品失败', error)
    ElMessage.error('批量删除药品失败')
  }
}

// 提交表单
const handleSubmit = async (data) => {
  try {
    // 处理价格，将元转换为分
    const submitData = { ...data }
    submitData.price = Math.round(submitData.price * 100)
    
    if (dialogConfig.isEdit) {
      // 编辑
      await updateMedicine(submitData)
      ElMessage.success('编辑成功')
    } else {
      // 添加
      await addMedicine(submitData)
      ElMessage.success('添加成功')
    }
    
    // 刷新列表
    getMedicineList()
    // 关闭对话框
    dialogConfig.visible = false
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}

// 切换到编辑模式
const switchToEdit = () => {
  dialogConfig.title = '编辑药品'
  dialogConfig.isEdit = true
  dialogConfig.isView = false
}

// 初始化
onMounted(async () => {
  await getCategoryList()
  getMedicineList()
})
</script>

<template>
  <div class="medicine-container">
    <el-card shadow="never" class="medicine-card">
      <template #header>
        <div class="card-header">
          <h3>药品信息管理</h3>
        </div>
      </template>
      
      <!-- 表格 -->
      <data-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :search-fields="searchFields"
        @add="handleAdd"
        @edit="handleEdit"
        @view="handleView"
        @delete="handleDelete"
        @batch-delete="handleBatchDelete"
        @refresh="getMedicineList"
      />
    </el-card>
    
    <!-- 表单对话框 - 添加/编辑 -->
    <dialog-form
      v-if="!dialogConfig.isView"
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="editFormFields"
      :rules="formRules"
      @submit="handleSubmit"
    />
    
    <!-- 表单对话框 - 查看 -->
    <dialog-form
      v-else
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="viewFormFields"
      :readonly="true"
      :show-confirm-button="false"
      :cancel-button-text="'关闭'"
    >
      <template #createTime="{ value }">
        {{ formatDateTime(value) }}
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogConfig.visible = false">关闭</el-button>
          <el-button type="primary" @click="switchToEdit">编辑</el-button>
        </div>
      </template>
    </dialog-form>
  </div>
</template>

<style scoped>
.medicine-container {
  height: 100%;
}

.medicine-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  flex: 1;
  overflow: auto;
  padding: 15px;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}
</style> 